﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;

using FXnaInfrastructure;

using System.Windows;


namespace GWApplication
{

    /// <summary>
    /// 为项目数据提供保存，获取数据等支持
    /// </summary>
    public  class ProjectService
    {
        protected ProjectService()
        {
 
        }

        static ProjectService currentService;

        public static ProjectService CurrentService
        {
            get {

                if (currentService==null)
                {
                    currentService = new ProjectService();
                    
                }
                
                return ProjectService.currentService;
            }
           
        }






        Project _project;

        public Project Project
        {
            get { return _project; }
            
        }



        #region 事件模型

        [field: NonSerialized]
        public event ProjHandler ProjChanged;


        #endregion


        #region 项目管理部分

        protected string projFileName = "";

        private bool m_bNullProj = true;

        /// <summary>
        /// 查看项目是否为关闭状态
        /// </summary>
        public bool BNullProj
        {
            get { return m_bNullProj; }

        }


        public bool Save()
        {
            //如果当前项目为空，则不返回
            if (this.m_bNullProj)
            {
                return false;

            }


            try
            {

                FileHelper.SaveToBinary(this.projFileName, _project);


            }
            catch (Exception e)
            {
                MessageBox.Show("保存错误："+e.Message);

                return false;

            }



            if (ProjChanged != null)
            {
                this.ProjChanged(ProjChangedType.SAVE);
            }

            return true;



        }

        public bool CloseProj()
        {
            projFileName = "";
            this.m_bNullProj = true;
            this._project = null;

            if (ProjChanged != null)
            {
                this.ProjChanged(ProjChangedType.CLOSE);
            }

            return true;

        }

        public bool Open(string projPathName)
        {
            try
            {
                this.projFileName = projPathName;


                _project = (Project)FileHelper.OpenFromBinary(this.projFileName);

                //这里需要添加关于软件版本号和项目文件版本号的判断问题，  版本不一致时给出提示信息，不需要做其它的纠错操作等
                //this.JudgeAppAndProjectVersion();


              

              
                


                m_bNullProj = false;

                this.reserveEvents();

                //激活对应的事件
                if (ProjChanged != null)
                {
                    this.ProjChanged(ProjChangedType.OPEN);
                }

                

                //Console.WriteLine(_mainData.ToString());
                return true;
            }
            catch (Exception ex)
            {

                MessageBox.Show("打开错误：" + ex.Message);

                return false;
            }
        }


        public bool CreateNew(string projPathName)
        {

            _project = new Project();

            //这里初始化一些常规设置

            ModflowCM cm = new ModflowCM("modflow");

            TLayer tl1 = new TLayer("layer1");

            cm.AddLayer(tl1);


            this._project.ConceptualData.Add(cm);


           


            projFileName = projPathName;

            //创建对应的工程用文件夹

            this.CreateDirectories();


            this.m_bNullProj = false;



            





            //订阅对应的事件
            this.reserveEvents();




            if (ProjChanged != null)
            {
                this.ProjChanged(ProjChangedType.NEW);
            }

            return true;

        }


        /// <summary>
        /// 订阅对应的事件模型
        /// </summary>

        protected void reserveEvents()
        {


        }


















        /// <summary>
        /// 创建对应的项目文件夹
        /// </summary>
        protected void CreateDirectories()
        {
            string path = this.GetProjPath() + this.GetProjName();

            //如果存在则删除其及子文件夹
            if (Directory.Exists(path))
            {
                Directory.Delete(path, true);
            }

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);

                

                //不在在一开始就创建子目录，而是在每次使用前，都从新判断并创建子目录


                //DirectoryInfo dirInfo = new DirectoryInfo(path);

                //dirInfo.CreateSubdirectory("solutions");
              



            }
        }

        /// <summary>
        /// 拷贝文件夹
        /// </summary>
        /// <param name="srcdir"></param>
        /// <param name="desdir"></param>
        private void CopyDirectory(string srcdir, string desdir)
        {
            string folderName = srcdir.Substring(srcdir.LastIndexOf("\\") + 1);

            string desfolderdir = desdir + "\\" + folderName;

            if (desdir.LastIndexOf("\\") == (desdir.Length - 1))
            {
                desfolderdir = desdir + folderName;
            }
            string[] filenames = Directory.GetFileSystemEntries(srcdir);

            foreach (string file in filenames)// 遍历所有的文件和目录
            {
                if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
                {

                    string currentdir = desfolderdir + "\\" + file.Substring(file.LastIndexOf("\\") + 1);
                    if (!Directory.Exists(currentdir))
                    {
                        Directory.CreateDirectory(currentdir);
                    }

                    CopyDirectory(file, desfolderdir);
                }

                else // 否则直接copy文件
                {
                    string srcfileName = file.Substring(file.LastIndexOf("\\") + 1);

                    srcfileName = desfolderdir + "\\" + srcfileName;


                    if (!Directory.Exists(desfolderdir))
                    {
                        Directory.CreateDirectory(desfolderdir);
                    }


                    File.Copy(file, srcfileName);
                }
            }
        }


        #endregion



        #region 项目辅助应用部分

        /// <summary>
        /// 返回工程所在目录,这里返回的值不包含工程的文件名子文件夹
        /// </summary>
        /// <returns></returns>
        public string GetProjPath()
        {

            return Path.GetDirectoryName(projFileName) + @"\";


        }


        /// <summary>
        /// 提供基本的目录索引服务
        /// </summary>
        /// <returns></returns>
        public string GetProjPath(ProjPath pathType)
        {
            switch (pathType)
            {

                
                   
                case ProjPath.WORKPATH:
                    return this.GetProjPath() + Path.GetFileNameWithoutExtension(this.projFileName) + "\\";

               case ProjPath.Images:

                    return this.GetProjPath(ProjPath.WORKPATH) + @"Images\";

               case ProjPath.Solutions:

                    return this.GetProjPath(ProjPath.WORKPATH) + @"solutions\";

               case ProjPath.Modflow:

                    return this.GetProjPath(ProjPath.Solutions) + @"modflow\";

                case ProjPath.ModflowInput:

                    return this.GetProjPath(ProjPath.Modflow) + @"input\";

                //case ProjPath.CCF:

                //    return this.GetProjPath(ProjPath.WORKPATH) + @"solutions\ccf\";


                default:
                    break;
            }

            return "";

        }


      

 
 

        /// <summary>
        /// 返回工程主文件的文件地址
        /// </summary>
        /// <returns></returns>
        public string GetProjMainFile()
        {
            return this.projFileName;
        }





        /// <summary>
        /// 返回不包含文件后缀名的工程名称,返回不具有扩展名的指定路径字符串的文件名。
        /// </summary>
        /// <returns></returns>
        public string GetProjName()
        {

            return Path.GetFileNameWithoutExtension(projFileName);

        }


     



        #endregion



    }
}
